<?php
namespace Pinenut\Service;

class UrlManager extends UrlRule {

	static $configClass = '\UrlRulesConfig';

	public $config;

	public $correctConfig;

	public function __construct( ) {
		$configClassName = static::$configClass;
		$this->config = $configClassName::get();
		$correctConfig = [];
		
		foreach ((array)@$this->config['rules'] as $key => $val) {
			if (is_array($val)) {
				$correctConfig[] = $val;
			} else {
				$correctConfig[] = [
					'class' => 'Standart',
					'action' => $val,
					'pattern' => $key
				];
			}
		}
		
		foreach ($correctConfig as $rules => $rule) {
			
			if (! empty($rule['class'])) {
				$nameOfClass = $rule['class'];
				$class = 'Pinenut\\Service\\UrlRule\\' . $nameOfClass;
				if (! class_exists($class, true)) {
					throw new \Exception('Wrong config url');
				}
				$urlRule = new $class($rule);
			}
			$this->rules[] = $urlRule;
		}
		// \Log::msg("rules",$this->rules);
	}

	/**
	 * Производим маршрутизацию, создаём по результатам запрос
	 * 
	 * @return \Pinenut\Request
	 */
	public function parseUrl($url = null, $method = null, $host = null, $params = null) {
		foreach ($this->rules as $urlRule) {
			/** @var \Request $request */
			$request = $urlRule->parseUrl($url, $method, $host, $params);
			
			if ($request !== false) {
				if (!$request->canExecute()) {
					throw new \Exception('Not acceptable', 406);
				}
				return $request;
			}
		}
		
		return false;
	}

	public function createUrl($action, array $params, $abs = false, $scheme = null) {
		
		foreach ($this->rules as $rule) {
			
			$url = $rule->createUrl($action, $params, $abs);
			
			if ($url !== false) {
				
				// если требуется абсолютный адрес - парсим урл 
				// и подменяем хост если его нет
				if ($abs) {
					$parsed_url = parse_url($url);
					
					if (null !== $scheme) {
						$parsed_url['scheme'] = $scheme;
					}
					if (empty($parser_url['host'])) {
						$domains = (array)$this->config['domains'];	
						$domains = (array)array_shift($domains);
						$parsed_url['host'] = array_shift($domains);
					}
					$url = static::unparse_url($parsed_url);
				}
				
				return $url;
			}
		}
	}
	
	
	static function unparse_url($parsed_url) {
		$scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . ':' : '';
		$host     = isset($parsed_url['host']) ? '//'.$parsed_url['host'] : '';
		$port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
		$user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
		$pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
		$pass     = ($user || $pass) ? "$pass@" : '';
		$path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
		$query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
		$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
		return "$scheme$user$pass$host$port$path$query$fragment";
	}
}